<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 订单管理
 * @author zxj
 *
 */
class Order extends MY_Controller {
	private $t_order = 'maintain_order';  //订单表
	function __construct() {
		parent::__construct();
        //加载维修订单模型
        $this->load->model('order_model','orderModel');
        $this->load->model('product_model');
        $this->load->model('package_model');
        $this->load->model('procurement_model');
	}


	/**
	 * 订单列表
	 */
	function index() {
        //获取表单数据
        $data = $formField = gp();
        if($data){
            //默认搜索来源单号
            if(!$data['diyKeyword'] && $data['diyValue']){
                $data['diyValue'] = trim($data['diyValue']);
                if(preg_match('/^1500\d+$/',$data['diyValue'])){
                    $data['diyKeyword']='source_int_id';
                }elseif(preg_match('/^[a-z]{2}\d*$/i',$data['diyValue'])){
                    $data['diyKeyword']='maintain_id';
                }else{
                    $customSearch = true;
                }
            }
            $formField[$data['diyKeyword']] = $data['diyValue'];
        }
        //默认select设置
        $optRepairSite[$data['repair_site_id']] = 'selected';
        $data['optRepairSite'] = $optRepairSite;

        $optOrigin[$data['website_origin']] = 'selected';
        $data['optOrigin'] = $optOrigin;

        $optRepairType[$data['maintain_type_id']] = 'selected';
        $data['optRepairType'] = $optRepairType;
        $optSite[$data['source_site_id']] = 'selected';
        $data['optSite'] = $optSite;
        $optStatus[$data['status_id']] = 'selected';
        $data['optStatus'] = $optStatus;
        $optKeyword[$data['diyKeyword']] = 'selected';
        $data['optKeyword'] = $optKeyword;
        $timeType = intval($data['timeType']);
        $ckTimeType[$timeType] = 'checked';
        $data['ckTimeType'] = $ckTimeType;

        /**
         * 自定义搜索
         */
        $diySerachFields = array(
            'maintain_id'=>lang('order_wxdh'),'source_int_id'=>lang('order_lydh'),
            'source_track_num'=>lang('order_lhzzh'),'track_num'=>lang('order_zzh'),'repairer'=>lang('order_wxy'),
            'add_user'=>lang('product_tjr'),'consumer_name'=>lang('order_khxm'),'consumer_phone'=>lang('order_khdh'),
            'consumer_email'=>lang('order_khyx'),'source_id'=>'webSourceId','consumer_address'=>'consumer_address'
        );
        $data['diySerachFields']= $diySerachFields;


        /**
         * 搜索逻辑处理
         */
        $where = $whereLike = array();
        //获取表字段(即查询条件,时间查询额外处理)
        $fieldsList = $this->db->list_fields($this->t_order);
        $fieldsList[] = 'startTime';
        $fieldsList[] = 'endTime';

        //需要模糊查询的字段
        $likeAry = array(
            'maintain_id','consumer_email','repairer','source_int_id',
            'source_id','source_track_num','track_num','consumer_name',
            'add_user','consumer_phone','consumer_address'
        );
        //拼接查询字符串
        $searchStr = 'orders/order/index/?';
        foreach ($formField as $key => $val) {
            if($val==='' || !in_array($key,$fieldsList))continue;
            $val = trim($val);
            if(in_array($key,$likeAry)){
                $whereLike[$key] = $val;
            }elseif($key == 'startTime'){
                if($timeType==1){
                    $where['enter_time >'] = $val;
                }else{
                    $where['add_time >'] = $val;
                }
            }elseif($key == 'endTime'){
                if($timeType==1){
                    $where['enter_time <'] = $val;
                }else{
                    $where['add_time <'] = $val;
                }
            }else{
                $where[$key] = $val;
            }
            $searchStr .= $key.'='.$val.'&';
        }
        $searchStr = $searchStr.'timeType='.$timeType;
		//分页
		$this->load->library('pagination');
		$config['page_query_string'] = TRUE;
		$config['base_url'] = blang_url($searchStr);
		$config['total_rows'] = $this->orderModel->countRows($this->t_order,$where,'',$whereLike);
		$config['per_page'] = $data['outputExcel']?5000:20;
        $page = max(1,intval($data['page']));
        $config['uri_segment'] = config_item('enable_lang')?5:4;
		$slimit = ($page - 1) * $config['per_page'];
		$this->pagination->initialize($config);
		$data['show_pages'] = $this->pagination->create_links();
		$num_page = ceil($config['total_rows']/$config['per_page']);
		$data['show_params'] = "总共{$config['total_rows']}条记录   {$config['per_page']}条/页   当前第{$page}/{$num_page}页";
		//查询
        if($customSearch===true){
            $sql = "select * from maintain_order where source_int_id like '%$val%' or  maintain_id like '%$val%' or source_track_num like '%$val%' or track_num like '%$val%' or consumer_email LIKE '%$val%' ";
            $datalist = $this->common_model->getQuery($sql, 'result_array');
        }else {
            $datalist = $this->orderModel->select($this->t_order, $slimit, $config['per_page'], 'enter_time desc', $where, '', $whereLike);
        }
        $roleArr = explode(',', $this->users['role_id']);
        if (in_array(5, $roleArr) && !$formField) {
            $status_id = $formField['status_id'] ? $formField['status_id'] : 6;
            $personList = $this->common_model->selectCustom($this->t_order, array('repairer' => $this->users['account'], 'status_id' => $status_id), 'enter_time asc');
            $datalist = array_merge($personList, $datalist);
        }

		//重构数据
		$newlist = array();
        $roleAry = array('zlj','zlj2','admin','prezwang','Julie','anna','guoyang');
        $roleArr = explode(',',$this->users['role_id']);
		foreach ($datalist as $key=>$vary) {
            //可以添加产品的权限
            if(in_array($this->users['account'],$roleAry)){
                $vary['is_add_cp'] = true;
            } elseif (in_array(2,$roleArr) && $vary['status_id'] == 1) {
                $vary['is_add_cp'] = true;
            }else{
                $vary['is_add_cp'] = false;
            }

            if($vary['repair_site_id']==6){
                $vary['is_add_cp'] = true;
            }

            $vary['id'] = $vary['maintain_id'];
            $vary['source_int_id'] = $vary['source_int_id']?$vary['source_int_id']:'/';
            //获取维修站点
            $repairSite = $this->orderModel->getRepiarSiteData($vary['repair_site_id']);
            $vary['repairSiteName'] = $repairSite['site_name'];
			//获取来源站点
			$siteFirst = $this->orderModel->getSiteData($vary['source_site_id']);
			$vary['siteName'] = $siteFirst?$siteFirst['source_site']:lang('order_bdcj');
            //获取维修类型
			$repairFirst = $this->orderModel->getRepairTypeData($vary['maintain_type_id']);
			$vary['repairName'] = $repairFirst?$repairFirst['maintain_type_name']:lang('order_sywx');
            //获取订单状态
            $statusFirst = $this->orderModel->getStatusData($vary['status_id']);
            $vary['statusName'] = $statusFirst?$statusFirst['status_name']:lang('order_djs');

            if($this->users['account']==$vary['repairer']){
                $vary['statusName'] = '<span style="color: #0033ff;">'.$vary['statusName'].'</span>';
            }

            $roleArr = explode(',', $this->users['role_id']);
            //当前操作员
            switch (intval($vary['status_id']))
            {
                case 1:
                    $vary['operator'] = $vary['add_user'];
                    break;
                case 2:
                    if (in_array(3, $roleArr) || in_array(4, $roleArr) || in_array(5, $roleArr) || in_array(9, $roleArr)) {
                        //if($this->users['role']=='repairer'){
                        $vary['operator'] = '<a href="'.blang_url('orders/order/jionOrder/'.$vary['maintain_id'].'/'.$page).'">'.lang('order_jd').'</a>';
                    }else{
                        $vary['operator'] = lang('order_ddjd');
                    }
                    break;
                default:
                    $vary['operator'] = $vary['repairer']?$vary['repairer']:'/';
            }
			$newlist[] = $vary;
		}
		$data['dataList'] = $newlist;
		//导出数据
		$data['outputUrl'] = blang_url($searchStr.'&outputExcel=true&page='.$page.'&timeType='.$timeType);
		if ($data['outputExcel']) {
            $fieldData = array(
                'maintain_id'=>lang('order_wxdh'),'siteName'=>lang('order_dhly'),'source_int_id'=>lang('order_lydh'),
                'repairName'=>lang('order_wxlx'),'statusName'=>lang('public_zt'),
                'add_time'=>lang('public_cjrq'),'repairer'=>lang('order_clr'),'account_origin'=>'accountOrigin',
                'source_id'=>'other order','consumer_name'=>'userName','consumer_email'=>'userEmail'
            );
            excel_output(lang('order_wxdh'),$fieldData,$newlist);
		}else{
            //获取所有维修站点
            $repairSiteList = $this->orderModel->getRepiarSiteData();
            $data['repairSiteList'] = $repairSiteList;
            //查询维修类型
            $repairTypeList = $this->orderModel->getRepairTypeData();
            $data['repairTypeList'] = $repairTypeList;
            //查询来源站点
            $siteList = $this->orderModel->getSiteData();
            $data['siteList'] = $siteList;
            //查询所有状态
            $statusList = $this->orderModel->getStatusData();
            $data['statusList'] = $statusList;
            //来源
            //website_origin
            $data['originList'] = array(
                '1'=>'pandaClever','2'=>'valukect','3'=>'rakuten','4'=>'pandawill',
                '5'=>'elephone','6'=>'aliexpress','7'=>'carrefour','8'=>'zopo',
                '9'=>'morefine','10'=>'freefeet','11'=>'geekvida_es','12'=>'geekvida_pt'
            );

			//视图以及样式
			$this->load->view('defaults/order_list',$data);
            $this->load->view('defaults/common/footer');
		}
	}


	/**
	 * 新增维修单
	 */
	function add(){
		//表单处理
		$data['post_type'] = __FUNCTION__;
		//插入数据
        $orderData = gp();
        gsh_output('已禁止',1);
		if ($orderData['submits'] && $orderData['maintain_id']) {
            $orderFirst = $this->orderModel->getOrderData($orderData['maintain_id']);
            if($orderFirst){
                show_goto('orders/order/','订单已存在，请搜索单号'.$orderFirst['maintain_id']);
            }
            $this->orderModel->addOrSetOrder($orderData);
            //生成订单轨迹
            $trackData = array(
                'maintain_id'=>$orderData['maintain_id'],'add_time'=>date('Y-m-d H:i:s'),
                'target_status'=>1,'modified_user'=>$this->users['account'],
            );
            $this->orderModel->set_order_track('',$trackData);
            show_goto('orders/order/','创建维修单成功!');
		}else{
            //查询所有维修站点
            $repairList = $this->orderModel->getRepiarSiteData();
            $data['repairList'] = $repairList;
            //维修类型
            $mtTypeList = $this->orderModel->getRepairTypeData();
            $data['mtTypeList'] = $mtTypeList;
            //状态
            $statusList = $this->orderModel->getStatusData('',array('status_id'=>1));
            $data['statusList'] = $statusList;

            //送货方式
            $data['shfsList'] = array('0'=>lang('order_sfzq'),'1'=>lang('order_kd'));
			//视图以及样式
			$this->load->view('defaults/order_post',$data);
			$this->load->view('defaults/common/footer');
		}
	}


    /**
     * 修改维修单
     * @param string $id  维修单ID
     */
	function edit($id='') {
		//表单处理
		$data['post_type'] = __FUNCTION__;
		//接收数据
        $id = empty($id)?gp('id'):$id;
        $orderFirst = $this->orderModel->getOrderData($id);
        if(!$id || !$orderFirst){
            show_goto('orders/order','订单不存在');
        }
        $data['orderFirst'] = $orderFirst;

        //数据
        $orderData = gp();

        //产品列表
        $productList = $this->orderModel->getProductList($id);
        if(!$productList && $orderData['status_id']>=2) {
            if ($orderFirst['source_id'] && intval($orderFirst['source_id'])) {
                redirect(blang_url('common/sitesSync/1/?id='.$orderFirst['source_id'].'&sitePrefix='.substr($id,0,2)));
            } else {
                show_goto('products/product/add/' . $id, '请先添加产品');
            }
        }

        //自动处理订单状态
        $refererPath = parse_url($_SERVER['HTTP_REFERER']);
        $refererPath = explode('/',$refererPath['path']);
        if($orderFirst['status_id']==4 || $orderData['status_id']==4 || (MYDEBUG=='true' && !$refererPath[4])) {
            /**
             * 自动同意报价
             */
            $signRule = array(
                'dhhtamz@outlook.com'=>'25',
                'aliexpress.sunny@gmail.com'=>'25',
                'kingkingkinguno@163.com'=>'40',
                'postventa@geekvida.es'=>'30',
                'newsletter@geekvida.pt'=>'30',
                'kundenservice@geekvida.de'=>'30',
                'pandawillmayorista@gmail.com'=>'30',
            );
            $agreePrice = $signRule[$orderFirst['consumer_email']];
            //报价单
            $priceOneList = $this->product_model->getPriceOne('',$id);
            if(!$priceOneList){
                show_goto('orders/order/inDetails/'.$id,'请先进行检测');
            }
            if($agreePrice){
                foreach ($priceOneList as $pc) {
                    if($pc['price_sort']!='EUR' && $pc['accessory_price']){
                        $pc['accessory_price'] = currency_service($pc['price_sort'],'EUR',$pc['accessory_price']);
                    }
                    $productFirst = $this->common_model->selectFirst('maintain_product',array('product_id'=>$pc['pid']));
                    if($pc['accessory_price']<=$agreePrice && $productFirst['is_guarantee']==1){
                        $productPurchaseData=$this->procurement_model->GetProductPurchaseData($pc['pid']);
                        $idlist=array();
                        foreach($productPurchaseData as $val){
                            $idlist[]=$val['id'];
                            $this->procurement_model->updatecg($val['id'],array('status'=>2));
                        }
                        $url="http://stock.dhhtgroup.com/webService/GetPublicInventoryRequirement.php";
                        CurlPost($url,$idlist);
                        $this->common_model->update('maintain_product_price',array('is_accept_price'=>1),array('pid'=>$pc['pid']));
                    }
                }
            }
            //速卖通保内同意维修
            if($orderFirst['website_origin']==6 || $orderFirst['source_site_id']=='9'){
                foreach ($productList as $rs) {
                    if($rs['is_guarantee']==1){
                        $productPurchaseData=$this->procurement_model->GetProductPurchaseData($rs['product_id']);
                        $idlist=array();
                        foreach($productPurchaseData as $val){
                            $idlist[]=$val['id'];
                            $this->procurement_model->updatecg($val['id'],array('status'=>2));
                        }
                        $url="http://stock.dhhtgroup.com/webService/GetPublicInventoryRequirement.php";
                        CurlPost($url,$idlist);
                        $this->common_model->update('maintain_product_price',array('is_accept_price'=>1),array('pid'=>$rs['product_id']));
                    }
                }
            }

            //是否自动同意报价
            $sql = 'select * from maintain_product_price where oid = \'' . $id . '\' and (is_accept_price=1 or is_accept_price=0) ;';
            $priceOneList = $this->common_model->getQuery($sql, 'result_array');
            if(MYDEBUG=='true'){
                gsh_output($priceOneList);
            }
            if (count($productList) == count($priceOneList)) {
                //修改订单状态  array_column  PHP version>5.5
                //$statusArr = array_column($priceOneList,'is_accept_price');
                foreach ($priceOneList as $rs) {
                    $statusArr[] = $rs['is_accept_price'];
                }
                if (in_array(0, $statusArr) && in_array(1, $statusArr)) {
                    $status_id = '25';
                } elseif (in_array(0, $statusArr)) {
                    $status_id = '24';
                } elseif (in_array(1, $statusArr)) {
                    $status_id = '23';
                }
                if (isset($status_id)) {
                    $this->editExtend($id, array('status_id' => $status_id));
                }
                js_goto(blang_url('orders/order/edit/'.$id));
            }
        }


        if ($orderData['submits'] && $id) {
            //修改运费
            $this->orderModel->update('maintain_product_price',array('freight_price'=>$orderData['freight_price']),array('oid'=>$id));

            //订单状态验证
            if($orderData['status_id'] == $orderFirst['status_id'] && MYDEBUG !== 'true'){
                $this->orderModel->addOrSetOrder($orderData,$id);
            }else{
                switch($orderData['status_id']){
                    case 2:
                        $qcReportList = $this->product_model->getQcReport('',$id);
                        if(!$qcReportList){
                            show_goto('orders/order/inDetails/'.$id,'请先进行质检');
                        }
                        $this->editExtend($id,$orderData);
                        if($orderFirst['website_origin']){
                            show_goto('maintainApi/PostOrder/post_flow_report/'.$id,'推送质检报告到tomrepair');
                        }elseif($orderFirst['source_site_id']!=1 && $orderFirst['source_site_id']!=8){
                            $this->syncQcReport($id);
                        }
                        break;
                    case 4:
                        $this->editExtend($id,$orderData);
                        if($orderFirst['source_site_id']==8){
                            show_goto('maintainApi/PostOrder/post_priceList/'.$id,'推送报价单到递四方');
                        }elseif($orderFirst['website_origin']){
                            show_goto('maintainApi/PostOrder/post_flow_price/'.$id,'推送报价单到tomrepair');
                        }elseif($orderFirst['source_site_id']!=1){
                            $this->syncPriceOne($id);//推送报价单到网站
                        }
                        break;
                    case 21:
                        /*
                        if($orderFirst['maintain_type_id']==8){
                            foreach ($productList as $rs) {
                                if(!$rs['sku']){
                                    show_goto('products/product/edit/'.$rs['product_id'],'请先完善产品SKU');
                                }
                            }
                            show_goto('orders/mgbarcode/addBarcode/'.$id,'生成条码入库');
                        }
                        */
                        $this->editExtend($id,$orderData);
                        break;
                    case 8:
                        $this->editExtend($id,$orderData);
                        if($orderFirst['source_site_id']==8){
                            show_goto('maintainApi/PostOrder/post_repairFinish/'.$id,'推送维修完成到递四方');
                        }
                        break;
                    case 7:
                        foreach ($productList as $rs) {
                            $peijianData = $this->orderModel->selectCustom('maintain_accessory',array('pid'=>$rs['product_id']));
                            if(!$peijianData){
                                show_goto('products/product/peijian/'.$rs['product_id'].'/'.$id,'请先添加配件需求');
                            }
                        }
                        $this->editExtend($id,$orderData);
                        break;
                    case 10:
                        if($orderFirst['website_origin']){
                            $this->orderModel->addOrSetOrder($orderData,$id);
                            $pushTrackRs = $this->setTracking($id);
                            if($pushTrackRs['error_code']!=100){
                                show_error($pushTrackRs);
                            }else{
                                $this->editExtend($id,$orderData);
                            }
                        }else{
                            $this->editExtend($id,$orderData);
                        }
                        if($orderData['repair_site_id']==1) {
                            if($orderData['delivery_country']=='ES' || $orderData['delivery_country']=='PT') {
                                if($orderData['delivery_zipcode']) {
                                    $this->AutoCreatePackage($id);
                                }
                            }
                        }
                        break;
                    default:
                        $this->editExtend($id,$orderData);
                }
            }
            show_goto('orders/order/','更新成功');
		}else{
            //gsh_output($orderFirst);
            //查询所有维修站点
            $repairList = $this->orderModel->getRepiarSiteData();
            $data['repairList'] = $repairList;
            $repairSiteFirst = $this->orderModel->getRepiarSiteData($orderFirst['repair_site_id']);
            $data['repairSiteFirst'] = $repairSiteFirst;
            //维修类型
            $mtTypeList = $this->orderModel->getRepairTypeData();
            $data['mtTypeList'] = $mtTypeList;
            //默认选中
            $optRepair[$orderFirst['repair_site_id']] = 'selected';
            $data['optRepair'] = $optRepair;
            $optMtType[$orderFirst['maintain_type_id']] = 'selected';
            $data['optMtType'] = $optMtType;
            $optStatus[$orderFirst['status_id']] = 'selected';
            $data['optStatus'] = $optStatus;
            $ckdDelivery[$orderFirst['delivery_service']] = 'selected';
            $data['ckdDelivery'] = $ckdDelivery;
            $ckdPickup[$orderFirst['pickup_service']] = 'checked';
            $data['ckdPickup'] = $ckdPickup;
            /**
             * 状态使用权限控制 
             */
            $statusFirst = $this->orderModel->getStatusData($orderFirst['status_id']);
            $statusList = $this->orderModel->getStatusData();
            $nextStatus = $statusFirst['next_status'];
            $nextStatus = explode(',',$nextStatus);
            //非退货单不能待质检，不能待入库
            if($orderFirst['maintain_type_id']!=8 && array_search('26',$nextStatus)){
                unset($nextStatus[array_search('26',$nextStatus)]);
            }
            if($orderFirst['maintain_type_id']!=8 && array_search('21',$nextStatus)){
                unset($nextStatus[array_search('21',$nextStatus)]);
            }elseif($orderFirst['maintain_type_id']==8 && $orderFirst['status_id']==1){
                unset($nextStatus[0]);
            }

            //角色可操作权限
            $userRole = $this->users['role_id'];
            $user_role_arr = explode(',' , $userRole);

            //查询出来不包含（客服,QC,拆包质检，超管和维修点经理）之外的所有权限id，也是为了防止以后还会有角色的增加
            //
            $roles = $this->common_model->getQuery('select `id` from `mt_role` where `id` not in( 1,2,3,6,10)' , 'result_array');
            //重构数组
            foreach ($roles as $k => $v) {
                $roles[$k] = $v['id'];
            }

            $roleArr = array();
            //print_r(count(array_intersect(array(1,2,3),array(4,5,6))));die('aa111');
            //客服,QC,拆包质检
            if (in_array(2 , $user_role_arr) || in_array(3 , $user_role_arr) || in_array(6 , $user_role_arr)) {
                $roleAry = array('1' , '2' , '9' , '10' , '11' , '21' , '6' , '26' , '22');
                //待接收,检测完成_待维修,维修中,出库质检,已发货,结束，评价,检测完成_待入库,入库完成,检测完成_待QC

                //以下这个判断是，客户除了【客服,QC,拆包质检】角色之外还有其他的非管理员角色
                //array_intersect取2个数组的交集
                if (count(array_intersect($user_role_arr , $roles)) > 0) {
                    array_push($roleAry , '3' , '4' , '6' , '7' , '8');
                }
            }
            else {
                $roleAry = array('3' , '4' , '6' , '7' , '8' , '27');
                //接单,已报价,维修中,维修中_等待配件,维修完成,装配完成_待QC
            }
            //超管和维修点经理
            if (in_array(1 , $user_role_arr) || in_array(10 , $user_role_arr)) {
                $roleAry = array('1' , '2' , '9' , '10' , '11' , '21' , '6' , '26' , '22' , '3' , '4' , '6' , '7' , '8' , '27');
            }
            //显示的状态数据
            $showStatus = array();
            foreach ($statusList as $key=>$row) {
                //当前状态
                if($row['status_id'] == $orderFirst['status_id']){
                    $showStatus[] = $row;
                }
                //可用状态
                if(in_array($row['status_id'],$nextStatus) && in_array($row['status_id'],$roleAry)){
                    $showStatus[] = $row;
                }
            }
            $data['statusList'] = $showStatus;

            //返修单状态
            if($orderFirst['maintain_type_id']==10){
                $status_id = intval($orderFirst['status_id']);
                $sql = 'select * from maintain_status where status_id in(2,6,7,8,9,10,21,22,'.$status_id.');';
                $statusList = $this->common_model->getQuery($sql, 'result_array');
                foreach ($statusList as &$rs) {
                    $rs['status_name'] = MYLANG == 'sc' ? $rs['status_name_cn'] : $rs['status_name_en'];
                }
                unset($rs);
                $data['statusList'] = $statusList;
            }


            //苹果机维修状态
            if($orderFirst['repair_site_id']==6){
                $status_id = intval($orderFirst['status_id']);
                $sql = 'select * from maintain_status where status_id in(4,8,21,22,'.$status_id.');';
                $statusList = $this->common_model->getQuery($sql, 'result_array');
                foreach ($statusList as &$rs) {
                    $rs['status_name'] = MYLANG == 'sc' ? $rs['status_name_cn'] : $rs['status_name_en'];
                }
                unset($rs);
                $data['statusList'] = $statusList;
            }

            if(MYDEBUG=='true' || $this->users['account']=='zlj'){
                $data['statusList'] = $statusList;
            }
            //送货方式
            $data['shfsList'] = array('0'=>lang('order_sfzq'),'1'=>lang('order_kd'));
			//视图以及样式
			$this->breadcrumb->append_crumb(array('url'=>'orders/order/edit/'.$id, 'name'=>lang('menu_xgdd')));
            $this->breadcrumb->append_crumb(
                array('url' => 'orders/order/inDetails/'.$id, 'name' => lang('order_fhdqdd'))
            );
            $this->load->view('defaults/order_post',$data);
            $this->load->view('defaults/common/footer');
		}
	}



    /**
     * 修改订单和维修轨迹
     * @param string $id
     * @param array $orderData
     * @return bool
     */
    function editExtend($id = '',$orderData=array()){
        if(!$id || !$orderData)return false;
        $this->orderModel->addOrSetOrder($orderData,$id);
        //维修轨迹
        $trackData = array(
            'maintain_id'=>$id,'add_time'=>date('Y-m-d H:i:s'),
            'target_status'=>$orderData['status_id'],'modified_user'=>$this->users['account']
        );
        $this->orderModel->set_order_track($id,$trackData);
    }





    /**
     * 查看订单详情
     * @param string $id
     * @return mixture
     */
    function inDetails($id=''){
        $id = empty($id)?gp('id'):$id;
        //获取订单信息
        $orderFirst = $this->orderModel->getOrderData($id);
        if(!$orderFirst){
            js_goto('','订单不存在',1);
        }

       //website_origin
        $originAry = array(
            '1'=>'pandaClever','2'=>'valukect','3'=>'rakuten','4'=>'pandawill',
            '5'=>'elephone','6'=>'aliexpress','7'=>'carrefour','8'=>'zopo',
            '9'=>'morefine','10'=>'freefeet','11'=>'geekvida_es','12'=>'geekvida_pt'
        );
        $orderFirst['website_origin'] = $originAry[$orderFirst['website_origin']];
        //加载产品分类模型
        $this->load->model('sort_model');
        //获取订单来源
        $siteFirst = $this->orderModel->getSiteData($orderFirst['source_site_id']);
        $orderFirst['siteName'] = $siteFirst?$siteFirst['source_site']:lang('order_bdcj');
        //获取维修类型
        $repairFirst = $this->orderModel->getRepairTypeData($orderFirst['maintain_type_id']);
        $orderFirst['repairName'] = $repairFirst['maintain_type_name'];
        //获取订单状态
        $statusFirst = $this->orderModel->getStatusData($orderFirst['status_id']);
        $orderFirst['statusName'] =$statusFirst['status_name'];
        $data['orderFirst'] = $orderFirst;

        //获取订单维修轨迹
        $trackList = $this->orderModel->getTrackList($id);
        foreach ($trackList as &$rs) {
            $rs['is_sync_yet'] = $rs['is_sync_yet']?'Yes':'No';
            $rs['status_name'] = MYLANG=='sc'?$rs['status_name_cn']:$rs['status_name_en'];
        }
        unset($rs);
        $data['trackList'] = $trackList;

        //获取订单下的产品
        $productList = $this->orderModel->getProductList($id);
        foreach ($productList as &$vary) {
            $sortFirst = $this->sort_model->get_sort($vary['sort_id']);
            $vary['sort_name'] = $sortFirst['sort_name'];
        }
        unset($vary);
        $data['productList'] = $productList;

        //获取订单质检报告
        $qcReportList = $this->product_model->getQcReport('',$id);
        $data['qcReportList'] = $qcReportList;

        //获取订单的报价单
        $priceOneList = $this->product_model->getPriceOne('',$id);
        $data['priceOneList'] = $priceOneList;

        //视图以及样式
        $this->breadcrumb->append_crumb(array('url'=>'orders/order/inDetails/'.$id, 'name'=>lang('order_ddxq')));
        $this->breadcrumb->append_crumb(array('url'=>'orders/order/edit/'.$id, 'name'=>lang('menu_xgdd')));
        $this->breadcrumb->append_crumb(array('url'=>'products/product/add/'.$id, 'name'=>'添加产品'));

        $this->load->view('defaults/order_inDetail',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 生成维修单号
     * @return string
     */
    function get_mtSite_id(){
        $maintain_id = $this->orderModel->createRepairId();
        $repairSiteFirst = $this->orderModel->getRepiarSiteData(gp('id'));
        echo json_encode(array('maintain_id'=>$maintain_id,'price_sort'=>$repairSiteFirst['price_sort']));
        exit;
    }


    /**
     * 接单
     * @param string $id
     */
    function jionOrder($id = ''){
        $id = empty($id)?gp('id'):$id;
        $orderFirst = $this->orderModel->getOrderData($id);
        if(!$orderFirst){
            show_goto('orders/order/','订单不存在');
        }
        //判断是否质检完成
        $rsQcReport = $this->product_model->getQcReport('',$id);
        if(!$rsQcReport){
            show_goto('orders/order/inDetails/'.$id,'当前订单还未质检，接单失败');
        }
        $arrrole = explode(',', $this->users['role_id']);
        if (!$this->users['account'] || (!in_array(5, $arrrole)) || $orderFirst['status_id'] >= 3) {
            show_goto('orders/order/', '非法操作!!!');
        }
        $setData = array('status_id'=>3,'repairer'=>$this->users['account']);
        $this->orderModel->addOrSetOrder($setData,$id);
        //更新订单轨迹
        $trackData = array(
            'maintain_id'=>$id,'add_time'=>date('Y-m-d H:i:s'),
            'target_status'=>3,'modified_user'=>$this->users['account'],
        );
        $this->orderModel->set_order_track($id,$trackData);
        show_goto('orders/order/inDetails/'.$id,'接单成功!');
    }



    /**
     * 推送质检报告
     * @param string $oid  维修单ID
     * @return bool
     */
    function syncQcReport($oid = ''){
        //查询当前订单
        $orderFirst = $this->orderModel->getOrderData($oid);
        if(!$orderFirst || !$orderFirst['repair_site_id']){
            show_error('推送质检报告失败');
        }
        if($orderFirst['website_origin']){
            show_goto('maintainApi/PostOrder/post_flow_report/'.$oid,'推送质检报告');
        }
        //获取当前维修站点
        $wxSite = $this->orderModel->selectFirst('mt_repair_site',array('id'=>$orderFirst['repair_site_id']));
        $params = array('sitePrefix'=>$wxSite['site_prefix']);
        //加载同步接口类
        $this->load->library('tomrepair',$params);
        //获取当前订单下的质检报告
        $pushData = $this->product_model->getQcReport('',$oid);
        foreach ($pushData as &$rs) {
            $rs['maintain_id'] = $rs['oid'];
            $rs['someorder_id'] = $orderFirst['source_id'];
            $rs['order_id'] = $orderFirst['source_int_id'];
            $rs['allof_maintaininfo_text'] = json_encode($rs);
        }
        unset($rs);
        //推送到网站
        $pushRs = $this->tomrepair->insertData('maintaininfo', $pushData);
        if ($pushRs && is_array($pushRs)) {
            //修改同步状态
            foreach ($pushRs as $key=>$val) {
                $this->orderModel->update('maintain_qcreport',array('is_sync'=>1,'maintaininfo_id'=>$key),array('pid'=>$val));
            }
        }
        if(MYDEBUG=='true'){
            var_dump($pushRs);
            gsh_output($pushData,1);
        }
        show_goto('orders/order/edit/'.$oid,'推送质检报告成功');
    }


    /**
     * 推送报价单
     * @param string $oid
     * @return bool
     */
    function syncPriceOne($oid = '')
    {
        //查询当前订单
        $orderFirst = $this->orderModel->getOrderData($oid);
        if(!$orderFirst || !$orderFirst['repair_site_id']){
            show_error('推送报价单失败');
        }
        if($orderFirst['website_origin']){
            show_goto('maintainApi/PostOrder/post_flow_price/'.$oid,'推送报价单');
        }
        //获取当前维修站点
        $wxSite = $this->orderModel->selectFirst('mt_repair_site',array('id'=>$orderFirst['repair_site_id']));
        $params = array('sitePrefix'=>$wxSite['site_prefix']);
        //加载同步接口类
        $this->load->library('tomrepair',$params);
        //获取订单的报价单
        $pushData = $this->product_model->getPriceOne('', $oid);
        foreach ($pushData as &$rs) {
            $qcReportFirst = $this->product_model->getQcReport($rs['pid']);
            if(!$qcReportFirst['maintaininfo_id']){
                gsh_output($rs['product_id'].'推送失败,请先推送质检报告');
                continue;
            }
            $productFirst = $this->product_model->get_product($rs['pid']);
            //$rs['maintain_totalprice'] = $rs['maintain_price']+$rs['accessory_price']+$rs['freight_price'];
            $rs['maintain_totalprice'] = 0;
            $rs['accessories_price'] = $rs['accessory_price'];
            $rs['shipping_price'] = $rs['freight_price'];
            $rs['labor_cost'] = $rs['maintain_price'];
            //$rs['someorder_id'] = $orderFirst['source_id'];
            $rs['someorder_id'] = $qcReportFirst['maintaininfo_id'];
            $rs['order_id'] = $orderFirst['source_int_id'];
            $rs['maintaininfo_id'] = $qcReportFirst['maintaininfo_id'];
            $rs['source_product_id'] = $rs['source_product_id'];
            $rs['status'] = 1;
            $rs['no_accept_price'] = $qcReportFirst['no_accept_price']+$rs['freight_price'];
            $rs['is_guarantee'] = $productFirst['is_guarantee'];
            if($productFirst['is_guarantee']==2){
                $rs['accessories_price'] = 0;
                $rs['labor_cost'] = 0;
            }
        }
        unset($rs);
        $pushRs = $this->tomrepair->insertData('maintainprice', $pushData);
        if(MYDEBUG=='true'){
            var_dump($pushRs);
            gsh_output($pushData,1);
        }
        show_goto('orders/order/','推送报价单报告成功');
    }


    /**
     * 删除订单
     * @param string $oid
     * @param string $page
     */
    function del($oid = '',$page = ''){
        $roleAry = array('zlj','zlj2','admin','prezwang','Julie','anna');
        if(!$oid || !in_array($this->users['account'],$roleAry)){
            show_goto('orders/order/','你没有权限这么做');
        }
        $where = array('maintain_id'=>$oid);
        $orderFirst = $this->orderModel->selectFirst($this->t_order,$where);
        if(!$orderFirst){
            show_goto('orders/order/','删除失败');
        }
        //删除产品
        $productList = $this->product_model->get_product('',$oid);
        foreach ($productList as $key=>$rs) {
            $this->product_model->deleteData($rs['product_id']);
        }
        //删除维修轨迹
        $this->orderModel->delete('maintain_track',$where);
        //删除订单
        $this->orderModel->delete($this->t_order,$where);
        redirect(blang_url('orders/order/index/?page='.intval($page)));
    }


    /**
     * 验证是否添加物料
     */
    function verifyIsMaterial(){
        $id = gp('id');
        $productList = $this->orderModel->getProductList($id);
        if(!$productList){
            json_output('','当前订单还未添加产品',false);
        }
        foreach ($productList as $rs) {
            $peijianData = $this->orderModel->selectCustom('maintain_accessory',array('pid'=>$rs['product_id']));
            if(!$peijianData){
                json_output('',lang('order_mypjsfjx'),false);
            }
        }
        json_output($productList,'已存在配件',true);
    }


    /**
     * 推送追踪号给david
     * @param string $oid
     * @return mixed|string
     */
    function setTracking($oid = ''){
        $oid = $oid?$oid:gp('oid');
        if (!$oid){
            show_error('The order ID can not be empty');
        }
        $oid = trim($oid);
        $orderFirst = $this->common_model->selectFirst($this->t_order,array('maintain_id'=>$oid));
        if(!$orderFirst || !$orderFirst['track_num']){
            show_error('track number not Null');
        }
        $url = "http://tomrepair.es/~tomrepair/api/setTracking";
        $data_to_post = array();
        $data_to_post['user'] = 'api@tomrepair.es';
        $data_to_post['token'] = '78de933bd0fbacf02ef2de1116e3338f1c627b07';
        $data_to_post['oid'] = $oid;
        $data_to_post['tracking'] = $orderFirst['track_num'];
        $headers[] = 'Authorization: DMCOHh3Y6Zf562MaDU3YzMyRjp3RFP9987trzdLZRZzcjFt';
        $headers[] = 'Content-Type: application/json; charset=utf-8';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data_to_post));
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            $result = curl_error($curl);
            gsh_output($data_to_post);
        }else{
            $result = json_decode($result,true);

        }
        curl_close($curl);
        return $result;
    }

    /**
     * 自动生成包裹
     * @param string $orderId
     */
    public function AutoCreatePackage($orderId=''){
        //订单数据
        $orderFirst = $this->orderModel->getOrderData($orderId);
        //产品列表
        $productList = $this->orderModel->getProductList($orderId);
        //产品id
        $product_id=array();
        //构建产品ID 兼容多个产品
        foreach($productList as $row){
            $product_id[]=$row['product_id'];
        }
        $product_id_str=implode(',',$product_id);
        $packagekData=array(
            'consignee'=>$orderFirst['consumer_name'],
            'zipcode'=>$orderFirst['delivery_zipcode']?$orderFirst['delivery_zipcode']:'',
            'city'=>$orderFirst['delivery_city']?$orderFirst['delivery_city']:'',
            'phone'=>$orderFirst['consumer_phone'],
            'country'=>$orderFirst['delivery_country']?$orderFirst['delivery_country']:'',
            'package_id'=>$orderFirst['maintain_id'].'_'.time(),
            'RECEIPT'=>$orderFirst['delivery_street_address']?$orderFirst['delivery_street_address']:'',
            'delivery_method'=>'Nacex',
            'order_id'=>$orderFirst['maintain_id'],
            'product_id'=>$product_id_str,
        );
        $addPackageBool=$this->package_model->AddPackageData($packagekData);
        if($addPackageBool){
            //修改产品状态改为已发货
            $this->product_model->UpdateProductStatus($product_id,$orderId);
        }
    }

}
